import React, { useEffect, useState } from 'react';
import {
  Button,
  Card,
  DatePicker,
  Descriptions,
  Form,
  Input,
  Modal,
  Select,
  Space,
  Table,
  type TableColumnsType,
  Tag,
  Tooltip,
} from '@nbase/ui';
import { EyeOutlined, SearchOutlined } from '@nbase/ui/icons';
import {
  type AuditLog,
  auditLogService,
  type QueryAuditLogDto,
} from '~/services/audit-log.service';
import {
  AUDIT_LOG_OPERATION_TYPE,
  AUDIT_LOG_OPERATION_TYPE_COLORS,
  AUDIT_LOG_OPERATION_TYPE_LABELS,
  PAGINATION,
} from '@nbase/shared';
import { formatDateTime } from '~/utils/format';
import {
  EMPTY_PLACEHOLDER,
  getHttpStatusColor,
  HTTP_METHOD_OPTIONS,
  INPUT_WIDTH,
  TABLE_COLUMN_WIDTH,
} from '~/constants';

const { RangePicker } = DatePicker;

/**
 * 审计日志页面
 * 只读页面，只提供查询功能
 */
const AuditLogManagement: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [dataSource, setDataSource] = useState<AuditLog[]>([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState<number>(PAGINATION.DEFAULT_PAGE_SIZE);
  const [searchForm] = Form.useForm();
  const [detailModalVisible, setDetailModalVisible] = useState(false);
  const [currentRecord, setCurrentRecord] = useState<AuditLog | null>(null);

  /**
   * 加载数据
   */
  const loadData = async (params?: QueryAuditLogDto) => {
    try {
      setLoading(true);
      const response = await auditLogService.getList({
        page,
        pageSize,
        ...params,
      });
      setDataSource(response.items);
      setTotal(response.total);
    } catch {
      // 错误已由 request.ts 统一处理
    } finally {
      setLoading(false);
    }
  };

  /**
   * 初始化加载
   */
  useEffect(() => {
    loadData();
  }, [page, pageSize]);

  /**
   * 搜索
   */
  const handleSearch = () => {
    const values = searchForm.getFieldsValue();
    const params: QueryAuditLogDto = {
      ...values,
    };

    // 处理日期范围
    if (values.dateRange && values.dateRange.length === 2) {
      params.startDate = values.dateRange[0].format('YYYY-MM-DD');
      params.endDate = values.dateRange[1].format('YYYY-MM-DD');
      delete (params as any).dateRange;
    }

    setPage(1);
    loadData(params);
  };

  /**
   * 重置搜索
   */
  const handleReset = () => {
    searchForm.resetFields();
    setPage(1);
    loadData();
  };

  /**
   * 查看详情
   */
  const handleViewDetail = async (record: AuditLog) => {
    try {
      setLoading(true);
      // 调用详情接口获取完整数据
      const detail = await auditLogService.getDetail(record.id);
      setCurrentRecord(detail);
      setDetailModalVisible(true);
    } catch {
      // 错误已由 request.ts 统一处理
    } finally {
      setLoading(false);
    }
  };

  /**
   * 关闭详情弹窗
   */
  const handleCloseDetail = () => {
    setDetailModalVisible(false);
    setCurrentRecord(null);
  };

  /**
   * 格式化 JSON 数据
   */
  const formatJson = (data: any): string => {
    if (!data) return EMPTY_PLACEHOLDER;
    try {
      if (typeof data === 'string') {
        return JSON.stringify(JSON.parse(data), null, 2);
      }
      return JSON.stringify(data, null, 2);
    } catch {
      return String(data);
    }
  };

  /**
   * 表格列定义
   */
  const columns: TableColumnsType<AuditLog> = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: TABLE_COLUMN_WIDTH.ID
    },
    {
      title: '用户名',
      dataIndex: 'username',
      key: 'username',
      width: TABLE_COLUMN_WIDTH.USERNAME,
      render: (text: string | null) => text || EMPTY_PLACEHOLDER,
    },
    {
      title: '操作模块',
      dataIndex: 'module',
      key: 'module',
      width: TABLE_COLUMN_WIDTH.NAME,
      render: (text: string | null) => text || EMPTY_PLACEHOLDER,
    },
    {
      title: '操作类型',
      dataIndex: 'operationType',
      key: 'operationType',
      width: TABLE_COLUMN_WIDTH.OPERATION_TYPE,
      render: (type: number) => (
        <Tag color={AUDIT_LOG_OPERATION_TYPE_COLORS[type as keyof typeof AUDIT_LOG_OPERATION_TYPE_COLORS]}>
          {AUDIT_LOG_OPERATION_TYPE_LABELS[type as keyof typeof AUDIT_LOG_OPERATION_TYPE_LABELS]}
        </Tag>
      ),
    },
    {
      title: '操作描述',
      dataIndex: 'description',
      key: 'description',
      width: TABLE_COLUMN_WIDTH.DESCRIPTION,
      ellipsis: true,
      render: (text: string | null) => text || EMPTY_PLACEHOLDER,
    },
    {
      title: '请求方法',
      dataIndex: 'method',
      key: 'method',
      width: TABLE_COLUMN_WIDTH.OPERATION_TYPE,
      render: (text: string | null) => text || EMPTY_PLACEHOLDER,
    },
    {
      title: '请求路径',
      dataIndex: 'path',
      key: 'path',
      width: TABLE_COLUMN_WIDTH.PATH,
      ellipsis: true,
      render: (text: string | null) => (
        <Tooltip title={text}>
          {text || EMPTY_PLACEHOLDER}
        </Tooltip>
      ),
    },
    {
      title: 'IP地址',
      dataIndex: 'ip',
      key: 'ip',
      width: TABLE_COLUMN_WIDTH.IP,
      render: (text: string | null) => text || EMPTY_PLACEHOLDER,
    },
    {
      title: '状态码',
      dataIndex: 'statusCode',
      key: 'statusCode',
      width: TABLE_COLUMN_WIDTH.OPERATION_TYPE,
      render: (code: number | null) => {
        if (!code) return EMPTY_PLACEHOLDER;
        return <Tag color={getHttpStatusColor(code)}>{code}</Tag>;
      },
    },
    {
      title: '耗时(ms)',
      dataIndex: 'duration',
      key: 'duration',
      width: TABLE_COLUMN_WIDTH.OPERATION_TYPE,
      render: (duration: number | null) => duration !== null ? duration : EMPTY_PLACEHOLDER,
    },
    {
      title: '操作时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      width: TABLE_COLUMN_WIDTH.DATETIME,
      render: (text: string) => formatDateTime(text),
    },
    {
      title: '操作',
      key: 'action',
      width: TABLE_COLUMN_WIDTH.ACTIONS,
      fixed: 'right',
      render: (_: any, record: AuditLog) => (
        <Space>
          <Button
            type="link"
            size="small"
            icon={<EyeOutlined />}
            onClick={() => handleViewDetail(record)}
          >
            详情
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <div>
      <Card>
        {/* 搜索表单 */}
        <Form form={searchForm} layout="inline" style={{ marginBottom: 16 }}>
          <Form.Item name="username" label="用户名">
            <Input placeholder="请输入用户名" allowClear style={{ width: INPUT_WIDTH.MD }} />
          </Form.Item>
          <Form.Item name="module" label="操作模块">
            <Input placeholder="请输入模块名" allowClear style={{ width: INPUT_WIDTH.MD }} />
          </Form.Item>
          <Form.Item name="operationType" label="操作类型">
            <Select placeholder="请选择操作类型" allowClear style={{ width: INPUT_WIDTH.MD }}>
              <Select.Option value={AUDIT_LOG_OPERATION_TYPE.QUERY}>查询</Select.Option>
              <Select.Option value={AUDIT_LOG_OPERATION_TYPE.CREATE}>新增</Select.Option>
              <Select.Option value={AUDIT_LOG_OPERATION_TYPE.UPDATE}>修改</Select.Option>
              <Select.Option value={AUDIT_LOG_OPERATION_TYPE.DELETE}>删除</Select.Option>
              <Select.Option value={AUDIT_LOG_OPERATION_TYPE.EXPORT}>导出</Select.Option>
              <Select.Option value={AUDIT_LOG_OPERATION_TYPE.IMPORT}>导入</Select.Option>
              <Select.Option value={AUDIT_LOG_OPERATION_TYPE.LOGIN}>登录</Select.Option>
              <Select.Option value={AUDIT_LOG_OPERATION_TYPE.LOGOUT}>登出</Select.Option>
              <Select.Option value={AUDIT_LOG_OPERATION_TYPE.OTHER}>其他</Select.Option>
            </Select>
          </Form.Item>
          <Form.Item name="method" label="请求方法">
            <Select placeholder="请选择方法" allowClear style={{ width: INPUT_WIDTH.SM }}>
              {HTTP_METHOD_OPTIONS.map(option => (
                <Select.Option key={option.value} value={option.value}>
                  {option.label}
                </Select.Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item name="path" label="请求路径">
            <Input placeholder="请输入路径" allowClear style={{ width: INPUT_WIDTH.LG }} />
          </Form.Item>
          <Form.Item name="ip" label="IP地址">
            <Input placeholder="请输入IP" allowClear style={{ width: INPUT_WIDTH.MD }} />
          </Form.Item>
          <Form.Item name="dateRange" label="操作时间">
            <RangePicker style={{ width: INPUT_WIDTH.XL }} />
          </Form.Item>
          <Form.Item>
            <Space>
              <Button type="primary" icon={<SearchOutlined />} onClick={handleSearch}>
                搜索
              </Button>
              <Button onClick={handleReset}>重置</Button>
            </Space>
          </Form.Item>
        </Form>

        {/* 表格 */}
        <Table
          columns={columns}
          dataSource={dataSource}
          rowKey="id"
          loading={loading}
          pagination={{
            current: page,
            pageSize,
            total,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条`,
            pageSizeOptions: PAGINATION.PAGE_SIZE_OPTIONS.map(String),
            onChange: (page, pageSize) => {
              setPage(page);
              setPageSize(pageSize);
            },
          }}
          scroll={{ x: 1600 }}
        />
      </Card>

      {/* 详情弹窗 */}
      <Modal
        title="审计日志详情"
        open={detailModalVisible}
        onCancel={handleCloseDetail}
        footer={[
          <Button key="close" onClick={handleCloseDetail}>
            关闭
          </Button>,
        ]}
        width={1000}
      >
        {currentRecord && (
          <Descriptions bordered column={2} size="small">
            <Descriptions.Item label="ID" span={2}>
              {currentRecord.id}
            </Descriptions.Item>
            <Descriptions.Item label="用户ID">
              {currentRecord.userId || EMPTY_PLACEHOLDER}
            </Descriptions.Item>
            <Descriptions.Item label="用户名">
              {currentRecord.username || EMPTY_PLACEHOLDER}
            </Descriptions.Item>
            <Descriptions.Item label="操作模块">
              {currentRecord.module || EMPTY_PLACEHOLDER}
            </Descriptions.Item>
            <Descriptions.Item label="操作类型">
              <Tag color={AUDIT_LOG_OPERATION_TYPE_COLORS[currentRecord.operationType as keyof typeof AUDIT_LOG_OPERATION_TYPE_COLORS]}>
                {AUDIT_LOG_OPERATION_TYPE_LABELS[currentRecord.operationType as keyof typeof AUDIT_LOG_OPERATION_TYPE_LABELS]}
              </Tag>
            </Descriptions.Item>
            <Descriptions.Item label="操作描述" span={2}>
              {currentRecord.description || EMPTY_PLACEHOLDER}
            </Descriptions.Item>
            <Descriptions.Item label="请求方法">
              {currentRecord.method || EMPTY_PLACEHOLDER}
            </Descriptions.Item>
            <Descriptions.Item label="请求路径">
              {currentRecord.path || EMPTY_PLACEHOLDER}
            </Descriptions.Item>
            <Descriptions.Item label="请求参数" span={2}>
              <pre style={{ margin: 0, maxHeight: 200, overflow: 'auto', background: '#f5f5f5', padding: 8, borderRadius: 4, whiteSpace: 'pre-wrap', wordBreak: 'break-all' }}>
                {formatJson(currentRecord.params)}
              </pre>
            </Descriptions.Item>
            <Descriptions.Item label="请求体" span={2}>
              <pre style={{ margin: 0, maxHeight: 200, overflow: 'auto', background: '#f5f5f5', padding: 8, borderRadius: 4, whiteSpace: 'pre-wrap', wordBreak: 'break-all' }}>
                {formatJson(currentRecord.body)}
              </pre>
            </Descriptions.Item>
            <Descriptions.Item label="状态码">
              {currentRecord.statusCode ? (
                <Tag color={getHttpStatusColor(currentRecord.statusCode)}>
                  {currentRecord.statusCode}
                </Tag>
              ) : EMPTY_PLACEHOLDER}
            </Descriptions.Item>
            <Descriptions.Item label="耗时">
              {currentRecord.duration !== null ? `${currentRecord.duration} ms` : EMPTY_PLACEHOLDER}
            </Descriptions.Item>
            <Descriptions.Item label="响应数据" span={2}>
              <pre style={{ margin: 0, maxHeight: 200, overflow: 'auto', background: '#f5f5f5', padding: 8, borderRadius: 4, whiteSpace: 'pre-wrap', wordBreak: 'break-all' }}>
                {formatJson(currentRecord.response)}
              </pre>
            </Descriptions.Item>
            <Descriptions.Item label="错误信息" span={2}>
              {currentRecord.errorMsg ? (
                <pre style={{ margin: 0, maxHeight: 200, overflow: 'auto', background: '#fff2f0', padding: 8, borderRadius: 4, color: '#cf1322', whiteSpace: 'pre-wrap', wordBreak: 'break-all' }}>
                  {currentRecord.errorMsg}
                </pre>
              ) : EMPTY_PLACEHOLDER}
            </Descriptions.Item>
            <Descriptions.Item label="IP地址">
              {currentRecord.ip || EMPTY_PLACEHOLDER}
            </Descriptions.Item>
            <Descriptions.Item label="User Agent">
              {currentRecord.userAgent || EMPTY_PLACEHOLDER}
            </Descriptions.Item>
            <Descriptions.Item label="创建人">
              {currentRecord.createdBy || EMPTY_PLACEHOLDER}
            </Descriptions.Item>
            <Descriptions.Item label="操作时间">
              {formatDateTime(currentRecord.createdAt)}
            </Descriptions.Item>
          </Descriptions>
        )}
      </Modal>
    </div>
  );
};

export default AuditLogManagement;
